package com.bw.bwskinfilecreator;

import com.bw.bwskinfilecreator.bean.ProjectConfigEntity;
import com.bw.bwskinfilecreator.bean.UtilConfigEntity;
import com.bw.bwskinfilecreator.utils.FileUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.*;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.bw.bwskinfilecreator.XxSKinUtil.*;


public class CreatorController {

    @FXML
    private CheckBox option1;

    @FXML
    private CheckBox option2;

    @FXML
    private CheckBox option3;


    @FXML
    private TextField factoryFolderTextField;


    @FXML
    private TextArea logTextArea;

    @FXML
    private Button btnCreate;

    @FXML
    private Button btnEdit;
    @FXML
    private Button btnDel;
    @FXML
    private Button btnCreator;
    private Stage dialogStage;
    @FXML
    private ComboBox<String> choiceBox;
    private ProjectConfigEntity projectConfigEntity;
    private Map<String, ProjectConfigEntity> projectConfigEntityMap;

    public void initialize() {
        loadUtilCache();
        loadProjectConfig();
    }

    @FXML
    private void handleFactoryBrowseButtonAction(ActionEvent event) {
        chooseDirectory(factoryFolderTextField, "选择皮肤Android工程路径");
    }

    @FXML
    private void handleNewProjectConfigButtonAction(ActionEvent event) {
        //弹出新建配置弹窗
        showCustomDialog(null);
    }

    @FXML
    private void handleEditProjectConfigButtonAction(ActionEvent event) {
        //弹出新建配置弹窗
        ProjectConfigEntity projectConfigEntity = null;
        if (projectConfigEntityMap != null) {
            projectConfigEntity = projectConfigEntityMap.get(choiceBox.getValue());
        }
        showCustomDialog(projectConfigEntity);
    }

    @FXML
    private void handleDelProjectConfigButtonAction(ActionEvent event) {
        //删除当前选中配置
        delProjectConfig(choiceBox.getValue());
    }

    private void showCustomDialog(ProjectConfigEntity projectConfigEntity) {
        // 创建对话框
        Dialog<Void> dialog = new Dialog<>();
        dialog.setTitle("项目配置");

        try {
            // 加载自定义布局
            FXMLLoader loader = new FXMLLoader(getClass().getResource("dialog_new_project_config.fxml"));
            dialog.getDialogPane().setContent(loader.load());
            ProjectConfigController dialogController = loader.getController();
            dialogController.initData(projectConfigEntity); // 传递数据到弹窗
            // 获取弹窗的Stage对象
            Stage dialogStage = (Stage) dialog.getDialogPane().getScene().getWindow();
            dialogController.setOnProjectActionListener(new ProjectConfigController.OnLiProjectActionListener() {
                @Override
                public void onSaveClick(ProjectConfigEntity projectConfigEntity) {

                    dialogStage.close();

                    //选择当前的配置
                    CreatorController.this.projectConfigEntity = projectConfigEntity;

                    //新增时追加选项
                    if (!projectConfigEntityMap.containsKey(projectConfigEntity.getProjectName())) {
                        choiceBox.getItems().add(projectConfigEntity.getProjectName());
                        choiceBox.getItems().sort(String::compareTo);
                    }
                    choiceBox.setValue(projectConfigEntity.getProjectName());
                    btnEdit.setDisable(false);
                    btnDel.setDisable(false);
                    btnCreator.setDisable(false);

                    saveProjectConfig(projectConfigEntity);
                }

                @Override
                public void onCancelClick() {
                    dialogStage.close();
                }

                @Override
                public void onLog(String msg) {
                    log(msg);
                }
            });


            // 监听窗口关闭请求（点击“X”时触发）
            dialogStage.setOnCloseRequest((WindowEvent event) -> {
                // 在这里添加关闭前的逻辑（如确认是否关闭）
                // 若允许关闭，无需处理；若禁止关闭，调用event.consume()

            });
            // 显示对话框
            dialog.showAndWait();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private void saveProjectConfig(ProjectConfigEntity projectConfigEntity) {
        if (projectConfigEntityMap == null) {
            projectConfigEntityMap = new HashMap<>();
        }
        //覆盖去重
        projectConfigEntityMap.put(projectConfigEntity.getProjectName(), projectConfigEntity);
        saveProjectConfigs2File();
    }

    /**
     * 删除配置
     *
     * @param projectName 项目名称
     */
    private void delProjectConfig(String projectName) {
        if (projectConfigEntityMap == null) return;
        projectConfigEntityMap.remove(projectName);

        saveProjectConfigs2File();

        choiceBox.getItems().remove(projectName);
        try {
            choiceBox.setValue(!choiceBox.getItems().isEmpty() ? choiceBox.getItems().get(0) : "");
            btnEdit.setDisable(choiceBox.getItems().isEmpty());
            btnDel.setDisable(choiceBox.getItems().isEmpty());
            btnCreator.setDisable(choiceBox.getItems().isEmpty());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveProjectConfigs2File() {
        if (projectConfigEntityMap == null) return;
        //保存数据到本地
        File file = new File(getProjectCachePath());
        FileUtils.createFileByDeleteOldFile(file);
        //将列表写入文件
        try {
            PrintWriter printWriter = new PrintWriter(file);
            printWriter.print(new Gson().toJson(new ArrayList<>(projectConfigEntityMap.values())));
            printWriter.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    private void chooseDirectory(TextField textField, String title) {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle(title);

        // 设置初始目录（可选）
        File initialDirectory = new File(textField.getText());
        directoryChooser.setInitialDirectory(initialDirectory);

        File selectedDirectory = directoryChooser.showDialog(dialogStage);

        if (selectedDirectory != null) {
            textField.setText(selectedDirectory.getAbsolutePath());
            logTextArea.appendText("已选择: " + selectedDirectory.getAbsolutePath() + "\n");
        }
    }

    @FXML
    private void handleHelpButtonAction(ActionEvent event) {
        //打开使用说明弹窗
        showClosableNoneAlert();
    }

    public void showClosableNoneAlert() {
        Alert alert = new Alert(Alert.AlertType.NONE);
        alert.setTitle("使用说明");
        String stringBuilder = "[注意事项]" + "\n" + "1.资源准备流程中会从Manifest文件读取包名,所以需要皮肤目录中的Manifest文件中包含package属性" + "\n" + "\n" + "[操作流程]" + "\n" + "(首次)准备一个能编译过的无用Android工程作为皮肤包制作的工程,建议使用AS重新创建" + "\n" + "\n" + "1.选择皮肤包制作工程路径" + "\n" + "示例:D:\\BWProject\\SkinFactory" + "\n" + "2.选择需要制作皮肤包的资源所在路径" + "\n" + "示例:D:\\BWProject\\E5\\SystemUI_Local_10\\systemui\\skin_temp\\systemui_skin" + "\n" + "3.选择本地用于上传该皮肤包的项目路径(不包含包名)" + "\n" + "示例:D:\\BWProject\\皮肤仓库\\SF5\\skinbags\\daytime_mode" + "\n" + "4.(单选)选择对应皮肤包名称" + "\n" + "5.(多选)选择生成皮肤包的后续操作" + "\n" + "6.点击生成皮肤";


        alert.setContentText(stringBuilder);
        // 获取弹窗的Stage对象
        Stage dialogStage = (Stage) alert.getDialogPane().getScene().getWindow();

        // 监听窗口关闭请求（点击“X”时触发）
        dialogStage.setOnCloseRequest((WindowEvent event) -> {
            // 在这里添加关闭前的逻辑（如确认是否关闭）
            // 若允许关闭，无需处理；若禁止关闭，调用event.consume()

        });

        alert.show();
    }

    @FXML
    private void handleExecuteButtonAction(ActionEvent event) {
        String factoryPath = factoryFolderTextField.getText();
        logTextArea.clear();

        new Thread(() -> new XxSKinUtil(new UtilConfigProvider() {
            @Override
            public String getSkinProjectPath() {
                return factoryPath;
            }

            @Override
            public ProjectConfigEntity getProject() {
                if (projectConfigEntityMap != null && !projectConfigEntityMap.isEmpty()) {
                    return projectConfigEntityMap.get(choiceBox.getValue());
                }
                return null;
            }

            @Override
            public int launchType() {
                int result = 0;
                if (option1.isSelected()) {
                    result |= TYPE_OPEN_EXPLORE;
                }

                if (option2.isSelected()) {
                    result |= TYPE_PUSH_TO_DEVICE;
                }

                if (option3.isSelected()) {
                    result |= TYPE_REPLACE_TO_GIT;
                }
                return result;
            }

            @Override
            public void onLog(String msg) {
                Platform.runLater(() -> log(msg));
            }
        }).launch()).start();

    }

    private String getTimeNow() {
        long currentTimeMillis = System.currentTimeMillis();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm:ss:SSS");
        return "[" + simpleDateFormat.format(new Date(currentTimeMillis)) + "] ";
    }

    private void log(String log) {
        logTextArea.appendText(getTimeNow() + log);
        logTextArea.appendText("\n");
    }

    /**
     * 加载项目配置
     */
    private void loadProjectConfig() {
        File file = new File(getProjectCachePath());
        if (file.exists()) {
            //文件存在，读取配置
            try {
                FileReader fileReader = new FileReader(file);
                if (projectConfigEntityMap == null) {
                    projectConfigEntityMap = new HashMap<>();
                }
                List<ProjectConfigEntity> projectConfigEntities = new Gson().fromJson(fileReader, new TypeToken<ArrayList<ProjectConfigEntity>>() {
                }.getType());
                List<String> chooses = new ArrayList<>();
                projectConfigEntities.sort(Comparator.comparing(ProjectConfigEntity::getProjectName));
                for (ProjectConfigEntity entity : projectConfigEntities) {
                    projectConfigEntityMap.put(entity.getProjectName(), entity);
                    chooses.add(entity.getProjectName());
                }
                log("加载项目配置完成");
                choiceBox.getItems().addAll(chooses);
                choiceBox.getItems().sort(String::compareTo);
                choiceBox.setValue(!projectConfigEntityMap.isEmpty() ? choiceBox.getItems().get(0) : "");

                btnEdit.setDisable(projectConfigEntityMap.isEmpty());
                btnDel.setDisable(projectConfigEntityMap.isEmpty());
                btnCreator.setDisable(projectConfigEntityMap.isEmpty());

            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private void loadUtilCache() {
        File file = new File(getUtilCachePath());
        if (file.exists()) {
            //文件存在，读取配置
            try {
                FileReader fileReader = new FileReader(file);
                UtilConfigEntity utilConfigEntity = new Gson().fromJson(fileReader, UtilConfigEntity.class);
                if (utilConfigEntity == null) return;
                //文件夹选择
                choiceBox.setValue(utilConfigEntity.getProjectConfigEntity().getProjectName());
                factoryFolderTextField.setText(utilConfigEntity.getSkinProjectPath());
                //功能选项
                option1.setSelected(utilConfigEntity.isNeedOpenExplore());
                option2.setSelected(utilConfigEntity.isNeedPushToDevice());
                option3.setSelected(utilConfigEntity.isNeedPushToGit());
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
    }
}